package mnnu.ghbe.service;

import mnnu.ghbe.entity.Death;
import mnnu.ghbe.entity.Event;
import mnnu.ghbe.entity.Game;
import mnnu.ghbe.entity.Ranking;
import mnnu.ghbe.entity.History;
import mnnu.ghbe.repository.DeathRepository;
import mnnu.ghbe.repository.GameRepository;
import mnnu.ghbe.repository.EventRepository;
import mnnu.ghbe.repository.RankingRepository;
import mnnu.ghbe.repository.HistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service
public class GameService {
    
    @Autowired
    private GameRepository gameRepository;
    
    @Autowired
    private EventRepository eventRepository;
    
    @Autowired
    private DeathRepository deathRepository;
    
    @Autowired
    private RankingRepository rankingRepository;
    
    @Autowired
    private HistoryRepository historyRepository;
    
    public Game startGame(Long userId) {
        // 检查用户是否已有游戏记录
        Optional<Game> existingGame = gameRepository.findByUserId(userId);
        if (existingGame.isPresent()) {
            // 删除现有游戏记录
            gameRepository.delete(existingGame.get());
        }
        
        // 创建新的游戏记录
        Game game = new Game();
        game.setUserId(userId);
        game.setCurrentAge(25); // 默认从18岁开始
        game.setBalance(10000.0); // 默认初始余额10000
        
        // 随机生成死亡年龄
        game.setDeathAge(generateRandomDeathAge());
        
        return gameRepository.save(game);
    }
    
    public Game getCurrentGameInfo(Long userId) {
        Optional<Game> gameOptional = gameRepository.findByUserId(userId);
        return gameOptional.orElse(null);
    }
    
    private int generateRandomDeathAge() {
        Random random = new Random();
        double probability = random.nextDouble();
        
        // 根据概率分布生成死亡年龄
        if (probability < 0.2) { // 25-35: 0.2
            return 25 + random.nextInt(11);
        } else if (probability < 0.3) { // 35-65: 0.1
            return 35 + random.nextInt(31);
        } else if (probability < 0.5) { // 65-75: 0.2
            return 65 + random.nextInt(11);
        } else if (probability < 0.9) { // 75-85: 0.4
            return 75 + random.nextInt(11);
        } else { // 85-95: 0.1
            return 85 + random.nextInt(11);
        }
    }
    
    public GameEventResult submitEvent(Long userId, Long eventId, Double withdrawAmount) {
        // 获取游戏记录
        Optional<Game> gameOptional = gameRepository.findByUserId(userId);
        if (!gameOptional.isPresent()) {
            throw new RuntimeException("游戏未初始化");
        }
        
        Game game = gameOptional.get();
        
        // 检查年龄是否达到死亡年龄
        if (game.getCurrentAge() >= game.getDeathAge()) {
            throw new RuntimeException("已达到死亡年龄，游戏结束");
        }
        
        // 获取事件
        Optional<Event> eventOptional = eventRepository.findById(eventId);
        if (!eventOptional.isPresent()) {
            throw new RuntimeException("事件不存在");
        }
        
        Event event = eventOptional.get();
        
        // 检查取款金额是否有效
        if (withdrawAmount < 0 || withdrawAmount > game.getBalance()) {
            throw new RuntimeException("取款金额无效");
        }
        
        // 保存取出金额用于计算
        Double withdrawn = withdrawAmount;
        Double remaining = game.getBalance() - withdrawAmount;
        
        // 随机决定事件结果（收益或亏损）
        Random random = new Random();
        double outcome = random.nextDouble();
        String description;
        double interestRate;
        String imageUrl = ""; // 新增图片URL字段

        if (outcome < event.getGainProbability()) {
            // 获得收益
            description = event.getGainDescription();
            interestRate = event.getGainAnnualInterestRate();
            imageUrl = event.getGainImage(); // 设置收益图片路径
        } else {
            // 遭受亏损
            description = event.getLossDescription();
            interestRate = event.getLossAnnualInterestRate();
            imageUrl = event.getLossImage(); // 设置亏损图片路径
        }
        
        // 计算增长年数
        int yearsToGrow = 10;
        boolean isDead = false;
        String deathDescription = "";
        String deathImage = "";
        
        // 检查余额是否为0，如果为0则直接结束游戏
        if (game.getBalance() <= 0) {
            isDead = true;
            deathDescription = "很遗憾，您的账户余额已耗尽，游戏结束";
            deathImage = "death.jpg";
            yearsToGrow = 0;
            
            // 更新排行榜和历史记录
            updateRanking(game.getUserId(), 0);
            
            // 保存游戏记录
            Game savedGame = gameRepository.save(game);

            // 构造返回结果
            GameEventResult result = new GameEventResult();
            result.setDescription("");
            result.setCurrentBalance(savedGame.getBalance());
            result.setDead(isDead);
            result.setDeathDescription(deathDescription);
            result.setDeathImage(deathImage);
            result.setHasRetirementBonus(false);
            result.setImgUrl("");
            result.setAnnualInterestRate(0.0);
            result.setCurrentAge(savedGame.getCurrentAge());

            return result;
        }
        
        // 检查10年后是否会超过死亡年龄
        if (game.getCurrentAge() + 10 >= game.getDeathAge()) {
            // 按照实际年数计算
            yearsToGrow = game.getDeathAge() - game.getCurrentAge();
            isDead = true;
            
            // 从数据库中随机获取一个死亡记录
            List<Death> deaths = deathRepository.findAll();
            if (!deaths.isEmpty()) {
                Death randomDeath = deaths.get(new Random().nextInt(deaths.size()));
                deathDescription = randomDeath.getDescription();
                deathImage = randomDeath.getImageName();
            } else {
                deathDescription = "很遗憾，您在" + game.getDeathAge() + "岁时去世了";
                deathImage = "death.jpg";
            }
        }
        
        // 计算收益/亏损
        // 取出的金额按事件利率计算
        double withdrawnAfterYears = withdrawn * Math.pow(1 + interestRate, yearsToGrow);
        
        // 剩余金额按银行存款利率计算（假设年利率为0.3%）
        double bankInterestRate = 0.003;
        double remainingAfterYears = remaining * Math.pow(1 + bankInterestRate, yearsToGrow);
        
        // 更新余额
        game.setBalance(withdrawnAfterYears + remainingAfterYears);
        
        // 增加年龄
        game.setCurrentAge(game.getCurrentAge() + yearsToGrow);
        
        // 如果到达退休年龄（65岁）则额外增加养老金
        boolean hasRetirementBonus = false;
        if (game.getCurrentAge() >= 65) {
            // 65岁及以后每年都会增加养老金
            double retirementBonus = 10000.0; // 固定养老金10000
            game.setBalance(game.getBalance() + retirementBonus);
            
            // 仅在刚到65岁时标记hasRetirementBonus为true
            if (game.getCurrentAge() - yearsToGrow < 65) {
                hasRetirementBonus = true;
            }
        }
        
        // 保存游戏记录
        Game savedGame = gameRepository.save(game);
        
        // 如果用户死亡，更新排行榜
        if (isDead) {
            updateRanking(savedGame.getUserId(), savedGame.getBalance().intValue());
        }
        
        // 构造返回结果
        GameEventResult result = new GameEventResult();
        result.setDescription(description);
        result.setCurrentBalance(savedGame.getBalance());
        result.setDead(isDead);
        result.setDeathDescription(deathDescription);
        result.setDeathImage(deathImage);
        result.setHasRetirementBonus(hasRetirementBonus); // 添加退休金标志
        result.setImgUrl(imageUrl); // 设置图片URL
        result.setAnnualInterestRate(interestRate); // 设置年利率
        result.setCurrentAge(savedGame.getCurrentAge()); // 设置当前年龄
        
        return result;
    }
    
    /**
     * 更新排行榜
     * @param userId 用户ID
     * @param score 分数（余额）
     */
    private void updateRanking(Long userId, Integer score) {
        Optional<Ranking> rankingOptional = rankingRepository.findById(userId.toString());
        Ranking ranking;
        
        if (rankingOptional.isPresent()) {
            // 如果已存在记录，则更新分数（取最大值）
            ranking = rankingOptional.get();
            if (score > ranking.getScore()) {
                ranking.setScore(score);
                rankingRepository.save(ranking);
            }
        } else {
            // 如果不存在记录，则创建新记录
            ranking = new Ranking();
            ranking.setUserId(userId);
            ranking.setScore(score);
            rankingRepository.save(ranking);
        }
        
        // 获取当前排名并保存历史记录
        List<Ranking> rankings = rankingRepository.findAllByOrderByScoreDesc();
        int currentRank = 0;
        for (int i = 0; i < rankings.size(); i++) {
            if (rankings.get(i).getUserId().equals(userId)) {
                currentRank = i + 1;
                break;
            }
        }
        
        // 保存历史记录
        Optional<Game> gameOptional = gameRepository.findByUserId(userId);
        Integer deathAge = null;
        if (gameOptional.isPresent()) {
            deathAge = gameOptional.get().getDeathAge();
        }
        History history = new History(userId, score, currentRank, deathAge);
        historyRepository.save(history);
    }
    
    public static class GameEventResult {
        private String description;
        private Double currentBalance;
        private boolean isDead;
        private String deathDescription;
        private String deathImage;
        private boolean hasRetirementBonus = false;
        private String imgUrl; // 新增图片URL字段
        private Double annualInterestRate; // 新增年利率字段
        private Integer currentAge; // 新增当前年龄字段
        
        public String getDescription() {
            return description;
        }
        
        public void setDescription(String description) {
            this.description = description;
        }
        
        public Double getCurrentBalance() {
            return currentBalance;
        }
        
        public void setCurrentBalance(Double currentBalance) {
            this.currentBalance = currentBalance;
        }
        
        public boolean isDead() {
            return isDead;
        }
        
        public void setDead(boolean dead) {
            isDead = dead;
        }
        
        public String getDeathDescription() {
            return deathDescription;
        }
        
        public void setDeathDescription(String deathDescription) {
            this.deathDescription = deathDescription;
        }
        
        public String getDeathImage() {
            return deathImage;
        }
        
        public void setDeathImage(String deathImage) {
            this.deathImage = deathImage;
        }
        
        public boolean isHasRetirementBonus() {
            return hasRetirementBonus;
        }
        
        public void setHasRetirementBonus(boolean hasRetirementBonus) {
            this.hasRetirementBonus = hasRetirementBonus;
        }
        
        // 新增图片URL字段的getter和setter方法
        public String getImgUrl() {
            return imgUrl;
        }
        
        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }
        
        // 新增年利率字段的getter和setter方法
        public Double getAnnualInterestRate() {
            return annualInterestRate;
        }
        
        public void setAnnualInterestRate(Double annualInterestRate) {
            this.annualInterestRate = annualInterestRate;
        }
        
        // 新增当前年龄字段的getter和setter方法
        public Integer getCurrentAge() {
            return currentAge;
        }
        
        public void setCurrentAge(Integer currentAge) {
            this.currentAge = currentAge;
        }
    }
}